﻿@page "/drawing/update/{Id}"

@inject IDrawingService DrawingService
@inject NavigationManager NavigationManager
@inject IJSRuntime JsRuntime

<PageTitle>更新图纸</PageTitle>

<div class="row">
    <div class="col">
        <p class="fs-5">更新图纸信息</p>
    </div>
    <CompDeleteIcon Roles="admin,pm,mgr" Click="Delete" />
</div>


<EditForm Model="_drawingDto" OnSubmit="Save">
    <div class="row">
        <div class="col input-group mb-2">
            <span class="input-group-text">Item编号</span>
            <input class="form-control" placeholder="Item" @bind-value="@_drawingDto.ItemNumber" />
        </div>
        <div class="col input-group mb-2">
            <span class="input-group-text">分批</span>
            <input class="form-control" type="number" @bind-value="@_drawingDto.Batch" />
        </div>
        <div class="col"></div>
        <div class="col"></div>
    </div>
    <MultiFileUpload Title="图纸(可添加多张)" FileType="application/pdf" @bind-MultiFileUrl="@_drawingDto.DrawingUrl" />

    <AuthorizeView Roles="admin">
        <Authorized Context="auth">
            <FileUpload Title="截图(测试用)" @bind-FileUrl="@_drawingDto.ImageUrl" />
        </Authorized>
    </AuthorizeView>

    <CompSaveCancelButtons CancelUrl="@($"drawings/{_drawingDto.ProjectId}")" />
</EditForm>


@code {
    [Parameter]
    public string Id { get; set; }
    private DrawingDto? _drawingDto = new();

    protected override async Task OnInitializedAsync()
    {
        var result = await DrawingService.GetFirstOrDefaultAsync(Guid.Parse(Id));
        _drawingDto = result.Result;
    }

    private async Task Delete()
    {
        //todo:检查图纸下有没有分段Module
        //if (await Http.GetFromJsonAsync<bool>($"api/Module/Exists/{drawing.Id}"))
        //{
        //    await JsRuntime.InvokeVoidAsync("alert", "该图纸下包含分段，不能删除！\n请先删除分段。");
        //    return;
        //}

        var confirmResult = await JsRuntime.InvokeAsync<bool>("confirm", $"确定要删除Item图纸【{_drawingDto.ItemNumber}】吗？");
        if (confirmResult)
        {
            var result = await DrawingService.DeleteAsync(Guid.Parse(Id));
            if (result.IsSuccessStatusCode) NavigationManager.NavigateTo($"drawings/{_drawingDto.ProjectId}");
        }
    }
    private async Task Save()
    {
        //为了避免Item号前后有空格，导致后续创建文件夹时出现错误，此处消除空格
        _drawingDto.ItemNumber = _drawingDto.ItemNumber.Trim();
        var result = await DrawingService.UpdateAsync(Guid.Parse(Id), _drawingDto);
        if (result.IsSuccessStatusCode) NavigationManager.NavigateTo($"drawings/{_drawingDto.ProjectId}");
    }
}
